<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Datei: card.class.php
 *
 * Class with all methodes for the shopping-cart
 *
 * @author Norbert Gebert
 * @copyright Norbert Gebert 25.09.2011
 * @license GPL3
 *
 * @version 0.5b
 * @package Admin
 * @subpackage global
 */
// Einbinden der Klasse
require('calculate.class.php');

class cart extends calculate
{

	private $_isProduct;
	private $_customer;
	private $_customerId;

	public function __construct($currency)
	{
		$this->setCurrency($currency);
		$this->_isProduct = 0;
		$this->_customer = ' ';
	}

	/**
	 * Get product to cart (only for actually session/user!)
	 * @param string $id Product-id
	 * @param option $name name of product
	 * @param option $number number of product to add (total)
	 * @param option $total  if true then number = total of pices
	 */
	public function add($id, $optionText, $number, $total = false)
	{
		db::getInstance()->where('product_id', $id);
		$resultp = db::getInstance()->getOne('product');

		if (db::getInstance()->count >= 1)
		{
			if (!isset($_SESSION['customernamex']) or $_SESSION['customernamex'] == '')
			{
				db::getInstance()->where('cart_product_id', $id);
				db::getInstance()->where('cart_session', $_SESSION['cartIdx']);
				$result = db::getInstance()->getOne('cart');
			}
			else
			{
				$this->_customer = $_SESSION['customernamex'];
				db::getInstance()->where('cart_product_id', $id);
				db::getInstance()->where('cart_customer_name', $this->_customer);
				$result = db::getInstance()->getOne('cart');
			}

			if (db::getInstance()->count >= 1)
			{ // product exist in cart
				if (!$total)
					$number += $result['cart_product_number'];

				if ($number > $resultp['product_stocks_quantity'])
					$number = $resultp['product_stocks_quantity'];

				if (!isset($_SESSION['customernamex']) or $_SESSION['customernamex'] == '')
				{
					$data = Array('cart_product_number' => $number);
					db::getInstance()->where('cart_product_id', $id);
					db::getInstance()->where('cart_session', $_SESSION['cartIdx']);
					db::getInstance()->update('cart', $data);
				}
				else
				{
					$data = Array('cart_product_number' => $number);
					db::getInstance()->where('cart_product_id', $id);
					db::getInstance()->where('cart_customer_name', $_SESSION['customername']);
					db::getInstance()->update('cart', $data);
				}
			}
			else
			{  // new entry in cart
				if ($number > $resultp['product_stocks_quantity'])
					$number = $resultp['product_stocks_quantity'];

				$data = array(
				 'cart_session' => $_SESSION['cartIdx'],
				 'cart_time' => time(),
				 'cart_product_id' => $id,
				 'cart_product_number' => $number,
				 'cart_product_text' => $optionText,
				 'cart_customer_name' => $this->_customer);
				db::getInstance()->insert('cart', $data);
				$this->_isProduct++;
			}
			$this->_refresh();
		}
	}

	/**
	 * Delete product from cart (only for actually session/user!)
	 * @param string $id Product-id
	 */
	public function delete($id)
	{
		if (!isset($_SESSION['customernamex']) or $_SESSION['customernamex'] == '')
		{
			db::getInstance()->where('cart_product_id', $id);
			db::getInstance()->where('cart_session', $_SESSION['cartIdx']);
			if (db::getInstance()->delete('cart'))
				$this->_isProduct--;
		}
		else
		{
			db::getInstance()->where('cart_product_id', $id);
			db::getInstance()->where('cart_customer_name', $_SESSION['customernamex']);
			if (db::getInstance()->delete('cart'))
				$this->_isProduct--;
		}

		$this->_refresh();
	}

	/**
	 * Refresh timstamp in cart 
	 */
	private function _refresh()
	{
		if (!isset($_SESSION['customernamex']) or $_SESSION['customernamex'] == '')
		{
			$data = Array('cart_time' => time());
			db::getInstance()->where('cart_session', $_SESSION['cartIdx']);
			db::getInstance()->update('cart', $data);
		}
		else
		{
			$data = Array('cart_time' => time());
			db::getInstance()->where('cart_customer_name', $_SESSION['customernamex']);
			db::getInstance()->update('cart', $data);
		}
		return;
	}

	/**
	 * returns numbers of products for guest / logged user
	 */
	public function isProduct()
	{
		// delete if out-of-time
		db::getInstance()->where('cart_time', (time() - CART_TIME), "<=");
		db::getInstance()->where('cart_customer_name', '');
		db::getInstance()->delete('cart');

		if (isset($_SESSION['customernamex']) and ! empty($_SESSION['customernamex']))
		{
			$this->_customer = $_SESSION['customernamex'];
			$nr = db::getInstance()->rawQuery("SELECT COUNT(1) AS number FROM cart WHERE " .
				"cart_customer_name = '" . $this->_customer . "'");

			$this->_isProduct = $nr[0]['number'];
		}
		else
		{
			$this->_customer = '';
			$nr = db::getInstance()->rawQuery("SELECT COUNT(*) AS number FROM cart WHERE " .
				"cart_session = '" . $_SESSION['cartIdx'] . "' AND " .
				"cart_customer_name = '" . $this->_customer . "'");
			$this->_isProduct = $nr[0]['number'];
		}
		return $this->_isProduct;
	}

	/**
	 * set customername for cart
	 */
	public function setCustomer($name)
	{
		$this->_customer = $name;
		$data = Array('cart_time' => time(), 'cart_customer_name' => $this->_customer);
		db::getInstance()->where('cart_session', $_SESSION['cartIdx']);
		db::getInstance()->update('cart', $data);
	}

	/**
	 * set customername for cart
	 */
	public function clearCustomer()
	{
		$this->_customer = '';
	}

	/**
	 * Returns an array with product-data
	 * sortet by tax-id
	 */
	public function getProducts()
	{
		$this->isProduct();

		if (isset($_SESSION['customernamex']) and ! empty($_SESSION['customernamex']))
		{
			$this->_customer = $_SESSION['customernamex'];
			db::getInstance()->where('cart_customer_name', $this->_customer);
			$result = db::getInstance()->get('cart');
		}
		else
		{
			$this->_customer = '';
			db::getInstance()->where('cart_session', $_SESSION['cartIdx']);
			$result = db::getInstance()->get('cart');
		}

		$cart = array();
		foreach ($result as $data)
		{
			$cols = Array('product_name', 'product_tax_id', 'product_sku', 'product_price_id');
			db::getInstance()->where('product_id', $data['cart_product_id']);
			$row = db::getInstance()->getOne('product', null, $cols);

			if (db::getInstance()->count >= 1)
			{
				$cart[] = array(
				 'priceId' => $row['product_price_id'],
				 'sku' => $row['product_sku'],
				 'product' => $row['product_name'],
				 'pricePerItem' => '-',
				 'priceTotal' => 0,
				 'taxTotal' => 0,
				 'optionsText' => $data['cart_product_text'],
				 'number' => $data['cart_product_number'],
				 'taxId' => $row['product_tax_id'],
				 'cart_product_id' => $data['cart_product_id']);
			}
		}
		return $this->_sortArrayByFields($cart, array('taxId' => SORT_DESC));
	}

	/**
	 * Returns a given array witch sorts for given filter(s)
	 * @param array  $arr Array to sort 
	 * @param array  $fields Array with commands like multisort() 
	 */
	public function optionsText2Html($optionsText)
	{
		$rows = explode(';', $optionsText);
		$html = '<br>';
		$first = FALSE;

		foreach ($rows as $row)
		{
			$value = explode('|', $row);

			switch ($value[0])
			{
				case '1': // Textrow
					$html .= $value[1] . ':<br>' . $value[2] . '<br>';
					break;
				case '2': // Textfield
					$html .= $value[1] . ':<br>' . $value[2] . '<br>';
					break;
				case '3': // Drop-Down
					$html .= $value[1] . ':<br>' . $value[2] . '<br>';
					break;
				case '4': // Option-List
					if ($first === FALSE)
					{
						$html .= $value[1] . ':<br>' . $value[2] . '<br>';
						$first = TRUE;
					}
					else
					{
						$html .= $value[2] . '<br>';
					}
					break;
				default:
					break;
			}
		}
		return $html;
	}

	/**
	 * Returns a given array witch sorts for given filter(s)
	 * @param array  $arr Array to sort 
	 * @param array  $fields Array with commands like multisort() 
	 */
	private function _sortArrayByFields($arr, $fields)
	{
		$sortFields = array();
		$args = array();

		foreach ($arr as $key => $row)
		{
			foreach ($fields as $field => $order)
			{
				$sortFields[$field][$key] = $row[$field];
			}
		}

		foreach ($fields as $field => $order)
		{
			$args[] = $sortFields[$field];

			if (is_array($order))
			{
				foreach ($order as $pt)
				{
					$args[$pt];
				}
			}
			else
			{
				$args[] = $order;
			}
		}
		$args[] = &$arr;
		@call_user_func_array('array_multisort', $args);
		return $arr;
	}

}

?>